# -*- coding: UTF-8 -*-
'nc4转tiff'
import os
import netCDF4 as nc
import numpy as np
from osgeo import gdal, osr
import glob
def nc2tif(data, Output_folder):
    pre_data = nc.Dataset(data)  # 利用.Dataset()读取nc数据

    #import os
    #os.environ['PROJ_LIB'] = r'D:\Anaconda3\Library\share\proj'
    #os.environ['GDAL_DATA'] = r'D:\Anaconda3\Library\share\gdal'

    #Lat_data = pre_data.variables['lat'][:]
    # print(Lat_data)
    #Lon_data = pre_data.variables['lon'][:]
    # print(Lon_data)
    Lon_data = pre_data.variables['lon'][:]
    Lat_data = pre_data.variables['lat'][:]

    pre_arr= np.asarray(pre_data.variables['precipitation'])#属性变量名
    #转给数组
    array = np.array(pre_arr)
    max_val = np.max(array)
    min_val = np.min(array)
    im_data = np.uint8((array - min_val) / max_val * 255)

    # 影像的左上角&右下角坐标
    Lonmin, Latmax, Lonmax, Latmin = [Lon_data.min(), Lat_data.max(), Lon_data.max(), Lat_data.min()]
    # Lonmin, Latmax, Lonmax, Latmin

    # 分辨率计
    Num_lat = len(Lat_data)
    Num_lon = len(Lon_data)
    Lat_res = (Latmax - Latmin) / (float(Num_lat) - 1)
    Lon_res = (Lonmax - Lonmin) / (float(Num_lon) - 1)
    # print(Num_lat, Num_lon)
    # print(Lat_res, Lon_res)

    for i in range(len(pre_arr[:])):
            # i=0,1,2,3,4,5,6,7,8,9,...
        # 创建tif文件
        driver = gdal.GetDriverByName('GTiff')
        out_tif_name = Output_folder + '\\' + data.split('\\')[-1].split('.')[0] + '_' + str(i + 1) + '.tif'
        out_tif = driver.Create(out_tif_name, Num_lon, Num_lat, 1, gdal.GDT_UInt16)

        # 设置影像的显示范围
        # Lat_re前需要添加负号
        geotransform = (Lonmin, Lon_res, 0.0, Latmax, 0.0, -Lat_res)
        out_tif.SetGeoTransform(geotransform)

        # 定义投影
        prj = osr.SpatialReference()
        prj.ImportFromEPSG(4326)
        out_tif.SetProjection(prj.ExportToWkt())

        # 数据导出
        out_tif.GetRasterBand(i+1).WriteArray(im_data[0].T)  # 将数据写入内存
        out_tif.FlushCache()  # 将数据写入到硬盘
        out_tif = None  # 关闭tif文件


def main():
    Input_folder = r'C:\Users\1\Desktop\test4'
    Output_folder = r'C:\Users\1\Desktop\test4'
    data_list = glob.glob(os.path.join(Input_folder, '*.nc4'))
    data_list.sort()
    # 读取所有数据
    # data_list = glob.glob(Input_folder + '*.nc')
    print(data_list)
    for i in range(len(data_list)):
        data = data_list[i]
        nc2tif(data, Output_folder)
        print(data + '转tif成功')

main()